package com.itxiao.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itxiao.config.RedisKeyConfig;
import com.itxiao.constants.Constants;
import com.itxiao.dao.UserAddressDao;
import com.itxiao.entity.User;
import com.itxiao.entity.UserAddress;
import com.itxiao.pojo.dto.AddAddressDto;
import com.itxiao.pojo.vo.R;
import com.itxiao.service.UserAddressService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * (UserAddress)表服务实现类
 *
 * @author makejava
 * @since 2025-10-12 17:16:47
 */
@Service
public class UserAddressServiceImpl extends ServiceImpl<UserAddressDao, UserAddress> implements UserAddressService {

    @Resource
    private UserAddressDao userAddressDao;
    @Resource
    private StringRedisTemplate template;

    @Override
    public R queryList(String token) {
        User sysUser = JSON.parseObject(
                template.opsForValue().get(RedisKeyConfig.AUTH_LOGIN_TOKEN + token),
                User.class
        );
        if (sysUser == null) {
            return R.fail("解析令牌失败");
        }
        List<UserAddress> addressList = userAddressDao.selectList(new LambdaQueryWrapper<>(UserAddress.class).eq(UserAddress::getUserId, sysUser.getId()));
        return R.ok(addressList);
    }

    @Override
    public R queryDefault(String token) {
        User sysUser = JSON.parseObject(
                template.opsForValue().get(RedisKeyConfig.AUTH_LOGIN_TOKEN + token),
                User.class
        );
        if (sysUser == null) {
            return R.fail("解析令牌失败");
        }
        UserAddress userAddress = userAddressDao.selectOne(new LambdaQueryWrapper<>(UserAddress.class).eq(UserAddress::getUserId, sysUser.getId())
                .eq(UserAddress::getIsDefault, Constants.IS_DEFAULT));
        if (userAddress == null) {
            return R.fail("查询默认地址失败");
        }
        return R.ok(userAddress);
    }

    @Override
    public R addOrUpdate(AddAddressDto dto, String token) {
        int addressId = 0;
        User sysUser = JSON.parseObject(
                template.opsForValue().get(RedisKeyConfig.AUTH_LOGIN_TOKEN + token),
                User.class
        );
        if (sysUser == null) {
            return R.fail("解析令牌失败");
        }
        if (dto.getId() > 0) {
            UserAddress userAddress = userAddressDao.selectById(dto.getId());
            if (userAddress == null) {
                return R.fail("地址信息不存在");
            }
            BeanUtils.copyProperties(dto, userAddress);
            int i = userAddressDao.updateById(userAddress);
            if (i <= 0) {
                return R.fail("修改地址失败");
            }
            addressId = userAddress.getId();
        } else {
            UserAddress userAddress = new UserAddress();
            BeanUtils.copyProperties(dto, userAddress);
            userAddress.setUserId(sysUser.getId());
            int insert = userAddressDao.insert(userAddress);
            if (insert <= 0) {
                return R.fail("插入地址失败");
            }
            addressId = userAddress.getId();
        }
        if (Constants.IS_DEFAULT == dto.getIsDefault()) {

            // 构造更新条件：同一个用户，非当前地址，且当前是默认的（可选）
            LambdaUpdateWrapper<UserAddress> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(UserAddress::getUserId, sysUser.getId())
                    .ne(UserAddress::getId, addressId)
                    .eq(UserAddress::getIsDefault, Constants.IS_DEFAULT);
            UserAddress updateObj = new UserAddress();
            updateObj.setIsDefault((long) Constants.NOT_DEFAULT);

            userAddressDao.update(updateObj, updateWrapper);
        }
        return R.ok();
    }

    @Override
    public R updateIsDefault(AddAddressDto dto, String token) {
        UserAddress userAddress = userAddressDao.selectById(dto.getId());
        if (userAddress == null) {
            return R.fail("地址信息不存在");
        }
        userAddress.setIsDefault((long) Constants.IS_DEFAULT);
        int i = userAddressDao.updateById(userAddress);
        if (i <= 0) {
            return R.fail("修改失败");
        }
        // 构造更新条件：同一个用户，非当前地址，且当前是默认的（可选）
        LambdaUpdateWrapper<UserAddress> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(UserAddress::getUserId, userAddress.getUserId())
                .ne(UserAddress::getId, userAddress.getId())
                .eq(UserAddress::getIsDefault, Constants.IS_DEFAULT);
        UserAddress updateObj = new UserAddress();
        updateObj.setIsDefault((long) Constants.NOT_DEFAULT);

        userAddressDao.update(updateObj, updateWrapper);
        return R.ok();
    }
}

